#include "database_system.h"

DatabaseSystem::DatabaseSystem()
    : executor_(catalog_), logger_(Logger::GetInstance())
{
    logger_.Info("DatabaseSystem initialized.");
}

QueryResult DatabaseSystem::execute_sql(const std::string &sql_string)
{
    logger_.Info("Received SQL: " + sql_string);
    try
    {
        // 步骤1：调用SQL编译器编译SQL
        CompileResult compile_res = SQLCompiler::compile(sql_string, catalog_.getAllSchemas());
        if (compile_res.status == "error")
        {
            // 编译失败：返回错误信息
            logger_.Error("Compile failed: " + compile_res.error.message);
            QueryResult err;
            err.status = "error";
            err.error_type = compile_res.error.error_type;
            err.message = compile_res.error.message;
            return err;
        }

        // 步骤2：调用执行引擎执行计划
        if (!compile_res.plan)
        {
            logger_.Error("Empty execution plan.");
            QueryResult err;
            err.status = "error";
            err.error_type = "Plan Error";
            err.message = "Empty execution plan.";
            return err;
        }
        return executor_.executePlan(*compile_res.plan);
    }
    catch (const std::exception &e)
    {
        logger_.Error("Exception: " + std::string(e.what()));
        QueryResult err;
        err.status = "error";
        err.error_type = "Exception";
        err.message = e.what();
        return err;
    }
}